{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "7feb4f40",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "  <td>\n",
    "    <a href=\"https://colab.research.google.com/github/nyandwi/machine_learning_complete/blob/main/7_intro_to_artificial_neural_networks_and_tensorflow/1_intro_to_neural_networks.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n",
    "  </td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c1ffa6b2",
   "metadata": {},
   "source": [
    "*This notebook was created by [Jean de Dieu Nyandwi](https://twitter.com/jeande_d) for the love of machine learning community. For any feedback, errors or suggestion, he can be reached on email (johnjw7084 at gmail dot com), [Twitter](https://twitter.com/jeande_d), or [LinkedIn](https://linkedin.com/in/nyandwi).*"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "304ad719",
   "metadata": {
    "id": "304ad719"
   },
   "source": [
    "<a name='0'></a>\n",
    "# Intro to Artificial Neural Networks and Deep Learning"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d281a995",
   "metadata": {
    "id": "d281a995"
   },
   "source": [
    "Deep Learning is the study of Artificial Neural Networks(ANNs). It is a subset of Machine Learning (ML), ML being a subset of Artificial Intelligence. \n",
    "\n",
    "Inspired by the human brain's biological neuron, ANNs has become the building block of modern intelligent systems, from our smartphones that can accurately identify our faces and voices, streaming services (like YouTube and Netflix) that know exactly what we want to watch, cars that can see the visual world and drive themselves, and not to mention AlphaGo that won world chess competition. \n",
    "\n",
    "\n",
    "This notebook will introduce a high level overview of Deep Learning. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b6a095ea",
   "metadata": {
    "id": "b6a095ea"
   },
   "source": [
    "## Contents \n",
    "\n",
    "* [1. Why Deep Learning](#1)\n",
    "* [2. A Single Layer Neural Network](#2)\n",
    "* [3. Activation Functions](#3)\n",
    "* [4. Types of Deep Learning Architectures](#4)\n",
    "    * [4.1 Densely Connected Networks](#4-1)\n",
    "    * [4.2 Convolutional Neural Networks](#4-2)\n",
    "    * [4.3 Recurrent Neural Networks](#4-3)\n",
    "    * [4.4 Transformers](#4-4)\n",
    "* [5. Challenges in Training Deep Neural Networks](#5)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4e73d1ca",
   "metadata": {
    "id": "4e73d1ca"
   },
   "source": [
    "<a name='1'></a>\n",
    "\n",
    "## 1. Why Deep Learning"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "be7730a3",
   "metadata": {
    "id": "be7730a3"
   },
   "source": [
    "Deep Learning is used to extract the patterns in (a huge amount of) data. Its potential has been seen in complex problems such as vision oriented and natural language. \n",
    "\n",
    "Let's take an example to develop more intuitive understanding of why deep learning has became so popular. Let's say that as an Engineer, you are asked by your city state to build a program that can recognize car and truck moving in a given road. The program can later be deployed in a less loads-road to warn trucks that pass there that the road was not designed for these types of vehicles. \n",
    "\n",
    "With normal programming, you would have to provide and to write all instructions (codes) of that particular program. The chance (close to reality) is that it would be hard, mostly because there are different types of cars and trucks and each can be unique in its ways, which can make it hard to write the rules forming such program. \n",
    "\n",
    "How can deep learning solve that? Well, by feeding the images of cars and trucks to a deep learning model, say a convolutional neural network (more on this latter), it can learn the underlying features of cars and trucks, and thus will be able to recognize each and each. We will see this in practice in later notebooks.\n",
    "\n",
    "With the advent of the computation power, both paid and free (Google Colab & Kaggle), open source datasets, and intelligent frameworks such as TensorFlow and PyTorch, it has become very much possible to do deep learning, even at personal level. This was not possible a decade ago. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c11149cb",
   "metadata": {
    "id": "c11149cb"
   },
   "source": [
    "<a name='2'></a>\n",
    "## 2. A Single Hidden Layer Neural Network"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a21b0198",
   "metadata": {
    "id": "a21b0198"
   },
   "source": [
    "<img src=\"https://upload.wikimedia.org/wikipedia/commons/3/3c/Neuralnetwork.png\" alt=\"Neuralnetwork.png\"><br> Image: A Single hidden layer neural network, Wikimedia"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "710bd0e6",
   "metadata": {
    "id": "710bd0e6"
   },
   "source": [
    "The image above represent a single hidden layer neural network. Usually, any typical neural network has 3 main layers:\n",
    "\n",
    "* **Input layer** that takes the input data. The input data can be image, text, or numbers but ofcourse whatever the data type is, the input to a neural network will always have to be in a numeric format. \n",
    "\n",
    "* **Hidden layer** that is between the input and the output layers. There is a alot of computations that takes place in this layer but that is not in the scope of this notebook. \n",
    "* **Output layer** that give the output of the network. Output can be a numerical number (mostly in regression problem) or a probability (mostly in classification problem). \n",
    "\n",
    "\n",
    "A neural network having more than one layer is commonly referred to `Deep Neural Network(DNN)`. Also, it is important to note that a neural network can have multiple input layers, multiple hidden layers, and multiple output layers. The structure of how a neural network has to be or its size will mostly depend on the type of a problem being solved. \n",
    "\n",
    "With the exception of the input layer, you will find something called activation function being applied to hidden and output layers. What is an activation function? "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a687f494",
   "metadata": {
    "id": "a687f494"
   },
   "source": [
    "<a name='3'></a>\n",
    "\n",
    "## 3. Common Activation Functions"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d6dc2881",
   "metadata": {
    "id": "d6dc2881"
   },
   "source": [
    "Activation functions are used to introduce nonlinearities in the network. I like to say that they dictate the output format of a given layer. \n",
    "\n",
    "Or simply put, these type of mathematical functions are used to make a decision of the layer's output. In later notebooks, this will certainly make sense. \n",
    "\n",
    "Here are the 3 most used activation functions:\n",
    "\n",
    "* **ReLU(Rectified Linear Unit)**: This is mostly used in hidden layers and it is a default activation function in most problems that will work well in most cases. ReLU always give the positive outputs, if the input number is greater than 0, the output will be that number. If it's less than 0, the output will be 0. The whole purpose of this type of activation function is to penalize the negative numbers. ReLu has different versions such as SeLU and LeakyReLU. In most cases, ReLU can only be used in output layer when the problem is a regression type, but this is not a necessity too. \n",
    "\n",
    "\n",
    "* **Sigmoid**: A sigmoid function gives the probabilistic output (a number between 0 and 1). It can be used in output layers of a classification problem. \n",
    "\n",
    "\n",
    "* **Softmax**: This type of function is also used in output classification layers, but instead of giving probalistic output, its output is an actual classes. This will make sense in later notebooks. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "df16a232",
   "metadata": {
    "id": "df16a232"
   },
   "source": [
    "<a name='4'></a>\n",
    "\n",
    "## 4. Types of Deep Learning Architectures"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "sKCDRk-PWEyK",
   "metadata": {
    "id": "sKCDRk-PWEyK"
   },
   "source": [
    "There are 4 main types of deep learning architectures. This is going to be a high level since they will be covered in the next notebooks."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "XqAdxSlWWe9m",
   "metadata": {
    "id": "XqAdxSlWWe9m"
   },
   "source": [
    "<a name='4-1'></a>\n",
    "\n",
    "### 4.1 Densely Connected Networks"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "WziQjYJWWJcT",
   "metadata": {
    "id": "WziQjYJWWJcT"
   },
   "source": [
    "\n",
    "\n",
    "\n",
    "Densely connected networks are made of stacks of layers from the input to the output. \n",
    "\n",
    "The units (or neurons) of any layer in that type of network are connected to all other units of the next layer. This is why they are also called fully connected layers. \n",
    "\n",
    "Densely connected layers are generally used for tabular data. Tabular data are these kinds of data that are in a tabular fashion. An example of tabular data is customer records: you have a column of names, roles, data joined, etc...\n",
    "\n",
    "\n",
    "![Densely connected.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1631359484854/ioMW08ea2.png)\n",
    "*Image: Densely connected networks*\n",
    "\n",
    "Dense layers are also used (in the combination of other architectures) as the last layer in either classification or regression problems. The right number of units in the last layer depends on the problem. Take an example: if you are classifying the news into 4 categories, then the last layer will have 4 units. If you are predicting the price of a house given its features, the last layer will have 1 unit. \n",
    "\n",
    "\n",
    "Dense networks are mostly used in simple tasks. When it comes to complex things like image recognition or text processing, they fail because they can't hold spatial features (in image) or can't learn a sequence in text for instance. But above all, the more deep they become, they tend to have many parameters which can results in having a big network/complex computations. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "GwF8_b5wWiye",
   "metadata": {
    "id": "GwF8_b5wWiye"
   },
   "source": [
    "<a name='4-2'></a>\n",
    "\n",
    "### 4.2 Convolutional Neural Networks"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3Eo0LrLsWP7B",
   "metadata": {
    "id": "3Eo0LrLsWP7B"
   },
   "source": [
    "CNN's, a.k.a Convnets are widely known as the go-to neural network architectures for computer vision tasks like image recognition and object detection, but they can also be used in other tasks such as texts and time series processing. \n",
    "\n",
    "Convnets are typically made of convolution, pooling layers, and fully connected layers at the end. Convolutional layers are used to extract the spatial features in images, and pooling layers are used to compress the resulted feature maps from convolution layers. And fully connected layers for classification purposes. \n",
    "\n",
    "![on-IOL-iG.png-2.webp](https://cdn.hashnode.com/res/hashnode/image/upload/v1630788206761/KF4gj3zPD.webp)\n",
    "*Image: Convnets architecture*\n",
    "\n",
    "Convnets are of 3 dimensions. The most popular one is Conv2D that is used in images and videos divided into frames. Conv1D is used in sequential data such as texts, time series, and sounds. A popular sound architecture called [WaveNet](https://deepmind.com/blog/article/wavenet-generative-model-raw-audio) is made of 10 stacked 1D Convnets.\n",
    "\n",
    "Conv3D is used in videos and volumetric images such as CT scans."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "w5-uILxvWuly",
   "metadata": {
    "id": "w5-uILxvWuly"
   },
   "source": [
    "<a name='4-3'></a>\n",
    "\n",
    "### 4.3 Recurrent Neural Networks (RNNs)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "73xeoLxvWVf3",
   "metadata": {
    "id": "73xeoLxvWVf3"
   },
   "source": [
    "\n",
    "The standard feedforward network (or call them densely connected network) maps the input to output. RNNs go beyond that. They can maintain the recurrence of data at each time step. \n",
    "\n",
    "\n",
    "![TF RNN.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1630789332991/7kzTaiwxp.png)\n",
    "*Image: Feed forward network vs recurrent neural networks*\n",
    "\n",
    "Due to their ability to preserve the recurrence of information, RNNs are commonly used in sequential data such as texts and time series. \n",
    "\n",
    "The basic RNN cells are not efficient at handling large sequences due to a short memory problem. They also suffer from [vanishing gradients](https://www.youtube.com/watch?v=qhXZsFVxGKo). \n",
    "\n",
    "The variant of RNNs that are able to handle long sequences is called Long Short Term Memory(LSTM). LSTM has also the ability to handle the sequences of variable lengths.  \n",
    "\n",
    "A special design difference about the LSTM cell is that it has a gate which is the basis of why it can control the flow of information over many time steps. \n",
    "\n",
    "In short, LSTM uses gates to control the flow of information from the current time step to the next time step in the following 4 ways: \n",
    "\n",
    "  * The input gate recognizes the input sequence.\n",
    "  * Forget gate gets rid of all irrelevant information contained in the input sequence and store relevant information in long term memory.\n",
    "  * LTSM cell updates update cell's state values.\n",
    "  * Output gate controls the information that has to be sent to the next time step. \n",
    "\n",
    "![Screen Shot 2021-09-01 at 09.22.56.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1630789390006/avzF2LKrK.png)\n",
    "\n",
    "*Image: LSTM architecture, [Intro to Deep Learning MIT](https://www.youtube.com/watch?v=BUNl0To1IVw&list=PLtBw6njQRU-rwp5__7C0oIVt26ZgjG9NI&index=5)*\n",
    "\n",
    "The ability of LSTMs to handle long-term sequences makes it a suitable neural network architecture for various sequential tasks such as text classification, sentiment analysis, speech recognition, image caption generation, machine translation. \n",
    "\n",
    "Another recurrent neural network that you will see is [Gate Recurrent Unit(GRU)](https://arxiv.org/pdf/1412.3555.pdf). GRU is a simplified version of LSTMs, and it's cheaper to train. \n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "JQzFWfYRW5hj",
   "metadata": {
    "id": "JQzFWfYRW5hj"
   },
   "source": [
    "<a name='4-4'></a>\n",
    "\n",
    "### 4.4 Transformers"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "94719993",
   "metadata": {
    "id": "94719993"
   },
   "source": [
    "\n",
    "Although recurrent neural networks are still used for sequential modeling, they have short-term memory problems when used for long sequences, and they are computationally expensive. The RNN's inability to handle long sequences and expensiveness are the two most motivations of transformers. \n",
    "\n",
    "Transformers are one of the latest groundbreaking researches in the natural language community. They are sorely based on the attention mechanisms that learn the relationships between words of the sentence and pays attention to the relevant words. \n",
    "\n",
    "One of the most notable things about transformers is that they don't use any recurrent or convolutional layers. It's just only attention mechanisms and other standard layers like embedding layer, dense layer, and normalization layers. \n",
    "\n",
    "They are commonly used in language tasks such as text classification, question answering, and machine translation. \n",
    "\n",
    "There have been [researches](https://arxiv.org/pdf/2101.01169.pdf) that show that they can also be used for computer vision tasks, such as image classification, object detection, image segmentation, and image captioning with [visual attention](https://arxiv.org/pdf/1502.03044.pdf). \n",
    "\n",
    "To learn more about the transformer, check out its awesome [paper](https://arxiv.org/pdf/1706.03762.pdf). \n",
    "\n",
    "\n",
    "![Screen Shot 2021-09-04 at 23.16.48.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1630790223290/99Ltf-fAy.png)\n",
    "\n",
    "*Image: Transformers architecture, [Attention Is All You Need](https://arxiv.org/pdf/1706.03762.pdf)*\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cd4c0136",
   "metadata": {
    "id": "cd4c0136"
   },
   "source": [
    "Below is a high level summary of the common neural networks architectures. \n",
    "\n",
    "![Deep Learning Architectures.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1631774267019/jzEyGcRBWM.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6db21482",
   "metadata": {
    "id": "6db21482"
   },
   "source": [
    "<a name='5'></a>\n",
    "\n",
    "## 5. Challenges in Training Neural Networks"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2c57ae94",
   "metadata": {
    "id": "2c57ae94"
   },
   "source": [
    "Training neural networks is a big challenge and this still an area of research. For example, how do you choose a right architecture? Although the type of data can tell the most architecture that should come into picture at first, it is not a trivial question. Take an example, we know CNN as image first algorithm, bit it has been used in some natural language processing and time series tasks and it can perform well. \n",
    "\n",
    "Also, deep learning models have many hyperparameters. Hyperparameters include things like number of layers, number of neurons, learning rate, activation functions, and optimizers (optimizers are used to reduce loss during training).  \n",
    "\n",
    "All these choises to be make it hard to train neural networks. Although there has been some techniques that can reduce number of choces to be made, [such as transfer learning which motivates reusing the pretrained models](https://jeande.tech/transfer-learning-explained), training this type of models is not an easy thing. \n",
    "\n",
    "If you would like to learn more about training neural networks, here is a great (but complex) material about it: [Why are deep neural networks hard to train?](http://neuralnetworksanddeeplearning.com/chap5.html). "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8f9156ea",
   "metadata": {
    "id": "8f9156ea"
   },
   "source": [
    "#### Also, before we go into hands-on deep learning in the next notebooks, I would like to invite you to play this game. Tinker with it and try to see how things like activation functions, input data, learning rate,...affects the neural network training. [***Here you Go!***](https://playground.tensorflow.org/#activation=tanh&batchSize=10&dataset=circle&regDataset=reg-plane&learningRate=0.03&regularizationRate=0&noise=0&networkShape=4,2&seed=0.93635&showTestData=false&discretize=false&percTrainData=50&x=true&y=true&xTimesY=false&xSquared=false&ySquared=false&cosX=false&sinX=false&cosY=false&sinY=false&collectStats=false&problem=classification&initZero=false&hideText=false). "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "475dc220",
   "metadata": {
    "id": "475dc220"
   },
   "source": [
    "### [BACK TO TOP](#0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "368cdfd5",
   "metadata": {
    "id": "368cdfd5"
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [],
   "name": "7.1 Intro to Artificial Neural Networks.ipynb",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3.7.10 64-bit ('tensor': conda)",
   "language": "python",
   "name": "python3710jvsc74a57bd034ac5db714c5906ee087fcf6e2d00ee4febf096586592b6ba3662ed3b7e7a5f6"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
